import { PageConfig } from 'next';
import an48 from '@mmstudio/an000048';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an49 from '@mmstudio/an000049';
import a002 from '../../../atoms/md5';
import { tbfduser } from '../../../atoms/db';

const logger = anylogger('pages/api/account/signup');

export type Result = boolean;

export type regtype = '1' | '2' | '3';

export type Message = {
	user: string;
	name: string;
	psw: string;
	phone: string;
	email: string;
}

/**
 * 用户注册
 */
const handler = an48<Result>();

handler.put(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { phone, psw, user, name, email } = req.body as Message;
		const e = await tbfduser().first('userid').where({
			userid: user
		});
		if (e) {
			const msg = encodeURIComponent('用户已存在');
			res.statusMessage = msg;
			res.status(500).json(false);
		} else {
			const md5 = a002(psw);
			await tbfduser().insert({
				userid: user,
				name,
				phone,
				psw: md5,
				email
			});
			res.status(200).json(true);
		}
	} catch (error) {
		logger.error(error);
		const msg = encodeURIComponent((error as Error).message);
		res.statusMessage = msg;
		res.status(500).json(false);
	}
});

export const config = {} as PageConfig;

export default handler;
